export function makeRender (options, formData, createElement) {
  const eles = options.map(item => {
    return createElement(item.componentName, makeParam(item, formData))
  })
  return options.map((item, index) => {
    return createElement('el-form-item', {
      props: {
        label: options[index].label
      }
    }, [eles[index]])
  })
}

export function makeParam (item, result = {}) {
  item.value = item.value || ''
  item.key = item.key || item.value
  result[item.key] = result[item.key] || item.value
  let props = { result }
  if (!item.componentName || (item.componentName).indexOf('el-') > -1) {
    Object.assign(props, makeProps(item))
  } else {
    props.options = makeProps(item)
  }
  return {
    props: {
      ...props,
      value: item.value
    },
    on: {
      input: (val) => {
        result[item.key] = val
      }
    }
  }
}

export function makeProps (options) {
  return Object.assign({}, options)
}

export function appSelect (item, createElement) {
  return createElement(item.compomentName, makeParam(item, {})
    // item.options.map(option => {
    //   return createElement('el-option', {
    //     props: makeProps(option)
    //   })
    // }, makeParam(item))
  )
}

export function initValue (config = {}, result = {}) {
  Object.keys(config).forEach(id => {
    const item = config[id]
    item.key && (result[item.key] = item.value || undefined)
  })
  return result
}

export function formatJson (str) {
  str = str.replace(/:\s+\/\//g, '://') // 去除空格 htt://
  let reg = /([{}])/g
  str = str.replace(reg, '\r\n$1\r\n')
  reg = /(,)/g
  str = str.replace(reg, '$1\r\n')
  reg = /:\r\n\{/g
  str = str.replace(reg, ': {')
  reg = /:\r\n\[/g
  str = str.replace(reg, ': [')
  reg = /:/g
  str = str.replace(reg, ': ')
  str = str.replace(/\r\n\r\n/g, '\r\n')
  let formatted = ''
  let pad = 0
  let PADDING = '   '
  let indent
  let padding
  const obj = str.split('\r\n')
  Object.keys(obj).forEach(key => {
    const node = obj[key]
    indent = 0
    padding = ''
    if (node.match(/\{$/) || node.match(/\[$/)) {
      indent = 1
    } else if (node.match(/\}/) || node.match(/\]/)) {
      if (pad !== 0) {
        pad -= 1
      }
    } else {
      indent = 0
    }
    for (let i = 0; i < pad; i++) {
      padding += PADDING
    }
    formatted += padding + node + '\r\n'
    pad += indent
  })
  return formatted.replace(/:\s+\/\//g, '://')
}
